package meijuli.com.join51.business.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.BankActivity;
import meijuli.com.join51.business.activity.SetPayPwdActivity;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.BankMsg;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.ui.ListDialog;
import meijuli.com.join51.business.ui.PayPwdDialog;
import meijuli.com.join51.business.utils.BankUtils;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import retrofit2.Call;

/**
 *
 *
 * @author wenqin 2017-05-05 15:25
 */

public class ShowBankFragment extends BaseFragment {

    private static final String KEY_BANK_MSG = "key_bank_msg";
    TextView mTextBankName;
    ImageView mChangeBank;
    TextView mBankNum;
    TextView mUserName;
    RelativeLayout mBankLayout;
    ImageView mIcon;

    private BankMsg mBankMsg;
    private Call<HttpResponse<String>> mCall;
    private Dialog mDialog;

    private PayPwdDialog mPayPWdDialog;

    public static ShowBankFragment newInstance(BankMsg bankMsg) {

        Bundle args = new Bundle();
        args.putSerializable(KEY_BANK_MSG, bankMsg);
        ShowBankFragment fragment = new ShowBankFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_show_bank_card, container, false);
        mTextBankName = view.findViewById(R.id.text_bank_name);
        mChangeBank = view.findViewById(R.id.change_bank);
        mBankNum = view.findViewById(R.id.bank_num);
        mUserName = view.findViewById(R.id.user_name);
        mBankLayout = view.findViewById(R.id.bank_layout);
        mIcon = view.findViewById(R.id.icon);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (getArguments() != null) {
            mBankMsg = (BankMsg) getArguments().getSerializable(KEY_BANK_MSG);
            if (mBankMsg == null) {
                return;
            }
            mUserName.setText(BankUtils.getRealName(mBankMsg.getRealName()));
            mBankNum.setText(BankUtils.getBankCard(mBankMsg.getBankCardNum()));
            mTextBankName.setText(mBankMsg.getBankName());

            Glide.with(getActivity())
                    .load(mBankMsg.getBankCardIco())
                    .error(R.mipmap.bank_logo)
                    .into(mIcon);
            initPayDialog(mBankMsg);
        }

        BankActivity bankActivity = (BankActivity) getActivity();
        bankActivity.setToolBarTitle("银行卡");

        mChangeBank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeBank();
            }
        });

        mBankLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                longClick();
                return false;
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            BankActivity bankActivity = (BankActivity) getActivity();
            bankActivity.setToolBarTitle("银行卡");
        }
    }

    private void initPayDialog(BankMsg bankMsg) {
        mPayPWdDialog = new PayPwdDialog(getActivity(), bankMsg);
        mPayPWdDialog.setOnListener(new PayPwdDialog.OnListener() {
            @Override
            public void onInputFinish(CharSequence text) {
                delBankCard(text.toString());
            }

            @Override
            public void onForgetClick(View view) {
                toResetPwdFragment();
            }
        });
    }

    private void toResetPwdFragment() {
        Intent intent = new Intent(getActivity(), SetPayPwdActivity.class);
        getActivity().startActivity(intent);
        getActivity().finish();
    }

    private void longClick() {
        mDialog = ListDialog.showDialog(getActivity(), new String[]{"删除"},
                new ListDialog.OnListItemClickListener() {
                    @Override
                    public void listItemClick(int position) {
                        requestIsSettingPwd();
                    }
                });
    }

    private void requestIsSettingPwd() {
        mCall = ApiManager.get().getApiService(ApiService.class).getPayPwd();
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                mPayPWdDialog.show();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
                if (errorCode == 6666) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    AlertDialog dialog = builder.setTitle("温馨提示")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton("现在去", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    toResetPwdFragment();
                                    dialog.dismiss();
                                }
                            })
                            .setMessage("您尚未设置交易密码，如需进行“删除银行卡”操作，请前往“交易密码”设置！")
                            .create();
                    dialog.setCancelable(false);
                    dialog.show();
                }
            }
        });
    }

    private void delBankCard(String pwd) {
        showLoadingDialog();
        mCall = ApiManager.get().getApiService(ApiService.class).delBankCard(mBankMsg.getDmId(),
                StringUtil.encodeToSHA256(pwd));
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                getActivity().finish();
                BankActivity.start(getActivity());
                ToastUtil.getInstance().showToast(getActivity(), "删除银行卡成功");
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    private void changeBank() {
        switchFragment(this, BindBankFragment.newInstance(false));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDialog != null) {
            mDialog.dismiss();
        }
        if (mPayPWdDialog != null) {
            mPayPWdDialog.dismiss();
        }
    }

}
